<style lang="scss">
.tab-ceil {
    text-align: center;
    a {
        color: #484848;
    }
}

.tab-ceil-active {
    a {
        color: #FF6600;
        font-weight: 400;
    }
}

.price-sel-container {
    width: 100%;
    padding-left: 8%;
    padding-top: 10px;
    padding-bottom: 10px;
    background-color: #dcdddf;
    // background-image: linear-gradient(to top, #c4c5c7 0%, #dcdddf 52%, #ebebeb 100%);
}

.tab-bar {
    width: 95%;
    margin: 0 auto;
    padding: 10px 0;
    border-bottom: solid 1px #dcdddf;
}

</style>

<template>
    <div>
        <v-affix>
			<div class="search-container">
				<search-box :keyWord="keyWord"></search-box>
			</div>
		</v-affix>

        <v-row class="tab-bar">
            <v-col class="tab-ceil" :class="isTmall?'':'tab-ceil-active'" span="6"><a @click="switchMall('all')">全部</a></v-col>
            <v-col class="tab-ceil" :class="isTmall?'tab-ceil-active':''" span="6"><a @click="switchMall('tmall')">天猫</a></v-col>
            <v-col class="tab-ceil" span="6">
                有券&nbsp;<v-switch size="small" v-model="hasCoupon"></v-switch>
            </v-col>
            <v-col class="tab-ceil" span="6"><a @click="switchPriceSelPanel">价格筛选</a></v-col>
        </v-row>
        
        <div class="price-sel-container" v-show="priceSelShow">
            <v-input style="width:30%;" placeholder="最低价" v-model="startPrice"/>
            <v-input style="width:30%;" placeholder="最高价" v-model="endPrice"/>
            <v-button @click="resetPrice">重置</v-button>
            <v-button @click="submitPrice">确认</v-button>
        </div>

        <v-row class="tab-bar">
            <v-col class="tab-ceil" :class="sort==''?'tab-ceil-active':''" span="6"><a @click="switchSort('')">综合</a></v-col>
            <v-col class="tab-ceil" :class="sort=='price_asc'?'tab-ceil-active':''" span="6"><a @click="switchSort('price_asc')">价格升序</a></v-col>
            <v-col class="tab-ceil" :class="sort=='price_des'?'tab-ceil-active':''" span="6"><a @click="switchSort('price_des')">价格降序</a></v-col>
            <v-col class="tab-ceil" :class="sort=='total_sales_des'?'tab-ceil-active':''" span="6"><a @click="switchSort('total_sales_des')">销量</a></v-col>
        </v-row>

        <div class="search-res-container">
            <item-card-row v-for="(item, index) in items" :key="index" :itemInfo="item"></item-card-row>
        </div>

        <return-back></return-back>
    </div>
</template>

<script>
import wx from 'weixin-js-sdk'
export default {
    data() {
        return {
            keyWord: '',
            hasCoupon: false,
            isTmall: false,
            startPrice: 0,
            endPrice: 0,
            sort: '',
            currentPage: 1,
            items: [],
            priceSelShow: false,
            onLoading: false
        }
    },

    mounted: function() {
        this.keyWord = this.$route.query.key_word
        // console.log("mounted..." + this.keyWord)
        // this.getSearchItems(function(){})
        this.scroll()
    },

    activated: function() {
        this.keyWord = this.$route.query.key_word
        this.scroll()
        this.getSignPackage()
    },

    watch: {
        hasCoupon(val) {
            console.log(val)
            this.refreshPageItems()
        },

        keyWord(val) {
            this.hasCoupon = false
            this.isTmall = false
            this.startPrice = 0
            this.endPrice = 0
            this.sort = ''
            this.currentPage = 1
            this.items = []
            this.priceSelShow = false
            this.onLoading = false
            this.getSearchItems(function(){})
            this.getSignPackage()
        }
    },

    methods: {
        getSearchItems: function(callback) {
            console.log("request search items.............")
            let that = this
            this.axios.get(`/api/item/material?platform_id=1&q=${this.keyWord}&page_no=${this.currentPage}&has_coupon=${this.hasCoupon}&is_tmall=${this.isTmall}&start_price=${this.startPrice}&end_price=${this.endPrice}&sort=${this.sort}`)
                .then(response => {
                    if (response.data.error) {
                        console.log(response.data.error)
                        callback()
						return
                    }
                    // console.log(response.data.tbk_dg_material_optional_response.result_list.map_data)
                    let items = response.data.tbk_dg_material_optional_response.result_list.map_data
                    for (let i=0; i<items.length; i++) {
                        let item = items[i]
                        // 通过商品是否有优惠券用来算出商品的最终价格
                        let coupon_final_price = item.coupon_amount ? (parseFloat(item.zk_final_price)-parseFloat(item.coupon_amount)).toFixed(2) : (parseFloat(item.zk_final_price)).toFixed(2)
                        item.coupon_final_price = coupon_final_price
                        that.items.push(item)
                    }
                    callback()
                })
        },

        refreshPageItems: function() {
            this.currentPage = 1
            this.items = []
            this.getSearchItems(function(){})
        },

        nextPageItems: function() {
            let that = this
            this.currentPage += 1
            this.getSearchItems(function(){
                that.onLoading = false
            })
        },

        switchMall: function(flag) {
            let original = this.isTmall
            if (flag == "all") {
                this.isTmall = false
            } else {
                this.isTmall = true
            }
            if (original != this.isTmall) {
                this.refreshPageItems()
            }
        },

        switchPriceSelPanel: function() {
            this.priceSelShow = !this.priceSelShow
        },

        resetPrice: function() {
            this.startPrice = 0
            this.endPrice = 0
        },

        submitPrice: function() {
            // 如果不是数字，直接return
            if (isNaN(this.startPrice) || isNaN(this.endPrice)) {
                return
            }
            this.refreshPageItems()
        },

        switchSort: function(sortStyle) {
            let original = this.sort
            this.sort = sortStyle
            if (original != this.sort) {
                this.refreshPageItems()
            }
        },

        scroll: function() {
			let that = this
            window.addEventListener('scroll', function() {
                if (!that.onLoading && (document.documentElement.offsetHeight + window.scrollY + 100 >= document.documentElement.scrollHeight)){
                    that.onLoading = true
                    // console.log("滚动到底部了。。。")
                    that.nextPageItems()
                }
            })
			// window.onscroll = function() {
			// 	if (!that.onLoading && (document.documentElement.offsetHeight + document.documentElement.scrollTop + 100 >= document.documentElement.scrollHeight)){
			// 		that.onLoading = true
			// 		// console.log("滚动到底部了。。。")
			// 		that.nextPageItems()
			// 	}
			// }
        },
        
        getSignPackage: function() {
			let currentUrl = window.location.href
			console.log(currentUrl)
			let urlArr = currentUrl.split("#")
      		let url = encodeURIComponent(urlArr[0])
			this.axios.get(`getAccess.php?url=${url}`)
				.then(res => {
					console.log(res)
					this.setWxConfig(res.data)
				})
				.catch(error => {
					console.log(error)
				})
		},

		setWxConfig: function(data) {
			let catName = this.keyWord
			let currentUrl = window.location.href
			wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: data.appId, // 必填，公众号的唯一标识
				timestamp: data.timestamp, // 必填，生成签名的时间戳
				nonceStr: data.nonceStr, // 必填，生成签名的随机串
				signature: data.signature,// 必填，签名
				jsApiList: [
					'onMenuShareTimeline',
					'onMenuShareAppMessage'
				] // 必填，需要使用的JS接口列表
			});
			wx.ready(function() {
				console.log('接口配置信息已经完成')
				wx.onMenuShareTimeline({
					title: catName,
					link: currentUrl,
					imgUrl: 'http://neimengweixin.cdn.xianyugame.com/66game/youhuiquan.jpg',
					success: function() {
						console.log('用户点击按钮回调')
					}
				})

				wx.onMenuShareAppMessage({
					title: catName, // 分享标题
					desc: `点击领取更多【${catName}】优惠券`, // 分享描述
					link: currentUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: 'http://neimengweixin.cdn.xianyugame.com/66game/youhuiquan.jpg', // 分享图标
					type: '', // 分享类型,music、video或link，不填默认为link
					dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
					success: function () {
						// 用户点击了分享后执行的回调函数
						console.log('用户点击了分享给朋友按钮')
					}
				})
			})
		},
        

        
    }
}
</script>

